<?php
/**
 * Created by JetBrains PhpStorm.
 * User: P2DC
 * Date: 10/7/2556
 * Time: 13:06 น.
 * To change this template use File | Settings | File Templates.
 */

if($_SERVER['REQUEST_METHOD']=='GET'){
    $pdo = Db::getPDO();
    try {
        $page_limit = isset($_GET['page_limit'])? $_GET['page_limit']: 20;
        $page_num = isset($_GET['page_num'])? $_GET['page_num']: 1;
        $q = isset($_GET['q'])? $_GET['q']: '';

        if(!empty($q)){
            $st = $pdo->prepare("SELECT * FROM IP WHERE ip LIKE :q ORDER BY ipLIMIT :start,:page_limit");
            $st->bindValue('q', '%'.$q.'%');
        } else {
            $st = $pdo->prepare("SELECT * FROM IP ORDER BY ip LIMIT :start,:page_limit");
        }
        $st->bindValue('start', ($page_num-1)*$page_limit, PDO::PARAM_INT);
        $st->bindValue('page_limit', $page_limit, PDO::PARAM_INT);
        $st->execute();

        $response = array();
        $response['data'] = $st->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($response);
    } catch(Exception $e) {
        $response = array();
        $response['error'] = array(
            'code'=> $e->getCode(),
            'message'=> $e->getMessage()
        );
        echo json_encode($response);
    }
}